package com.nwpu.hass.repository;

import com.nwpu.hass.domain.DeviceEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 设备信息的持久化
 *
 * @author wjy
 * @version v1.0.0
 */
@Repository
public interface DeviceRepository extends JpaRepository<DeviceEntity, Long> {

    /**
     * 查找所有的特定type和family的设备，并按使用次数从小到大排序
     *
     * @param type 设备型号
     * @param family 设备家族
     * @return 符合要求的设备列表
     */
    @Query(nativeQuery = true, value = "select * from device where status = 0 and type = ?1 " +
            "and family = ?2 and deviceName = ?3 order by usedtimes")
    List<DeviceEntity> findAllByTypeAndFamilyAndDeviceNameOrderByUsedTimes(String type, String family, String deviceName);

    /**
     * 查找所有借出待审核设备
     * @return 设备列表
     */
    @Query(nativeQuery = true, value = "select * from device where status = -1 limit ?1,?2")
    List<DeviceEntity> findBorrowing(Integer min, Integer max);

    /**
     * 查找所有归还待审核设备
     * @return 设备列表
     */
    @Query(nativeQuery = true, value = "select * from device where status = -2 limit ?1,?2")
    List<DeviceEntity> findReturning(Integer min,Integer max);

    /**
     * 查找所有处于报修申请状态的设备
     * @return
     */
    @Query(nativeQuery = true, value = "select * from device where status = -3 limit ?1,?2")
    List<DeviceEntity> findRepairing(int min, int max);

    DeviceEntity findDeviceEntityByDeviceId(Long deviceId);

    /**
     * 查找所有位置为空的设备
     *
     * @return 设备列表
     */
    @Query(nativeQuery = true, value = " select * from device where position is null limit ?1,?2")
    List<DeviceEntity> findAllByPositionIsNull(int offset,int max);

    /**
     * 通过设备状态查找设备列表,并且指定使用次数下限
     * @return 满足设备状态的设备集合
     */
    @Query(nativeQuery = true, value = "select * from device where status = 0 and usedTimes > 0")
    List<DeviceEntity> findByStatusAndUsedTimesGreaterThan(int status, int greater);

    DeviceEntity findByDeviceIdAndStatus(Long deviceId,int status);

    @Query(nativeQuery = true, value = "select * from device limit ?1,?2")
    List<DeviceEntity> findAllDevices(int min,int max);

    List<DeviceEntity> findAllByFamily(String family);

    List<DeviceEntity> findAllByStatus(int status);

    @Query(nativeQuery = true, value = "select * from device where status=-4 limit ?1,?2")
    List<DeviceEntity> findPageableOnScrapedDevices(int rowoffset,int max);


}
